package d0626;

import java.sql.*;

public class 事务管理 {

	// 案例: 新增一个部门, 同时给该门添加2个员工
	/**
	 * 
	 * @param dname  新增部门名
	 * @param enames 员工姓名数组
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	public void addDept(int deptno, String dname, int empno, String[] enames)
			throws ClassNotFoundException, SQLException {
		String sql1 = "insert into dept values(?,?,null)";
		String sql2 = "insert into emp (empno, ename,deptno) values (?,?,?)";

		Class.forName("oracle.jdbc.driver.OracleDriver");

		// 获取连接   本地地址 :  localhost(域名)   127.0.0.1(ip地址)  1521 默认端口
		String url = "jdbc:oracle:thin:@//127.0.0.1:1521/orcl";
		String user = "scott";
		String password = "a";
		Connection conn = DriverManager.getConnection(url, user, password);
		// 取消自动提交自动提交
		conn.setAutoCommit(false);

		try {
			PreparedStatement ps1 = conn.prepareStatement(sql1);
			PreparedStatement ps2 = conn.prepareStatement(sql2);

			// 新增部门
			ps1.setInt(1, deptno);
			ps1.setString(2, dname);
			ps1.executeUpdate();

			// 产生数学异常==> 运行时异常
			// int a = 1 / 0;

			for (int i = 0; i < enames.length; i++) {
				ps2.setInt(1, empno);
				ps2.setString(2, enames[i]);
				ps2.setInt(3, deptno);
				ps2.executeUpdate();
				empno++;
			}
			// 执行提交
			conn.commit();
		} catch (Exception e) {
			// 执行回滚
			conn.rollback();
			// 继续抛出异常
			throw e;
		} finally {
			// 关闭连接
			conn.close();
		}

	}

}
